#!/bin/bash

# wmctrl -l 可以查看窗口名

appToggle() {
    # 入参只能有一个
    if [ $# -gt 1 ];then
        echo "parameter numbers should only be one"
        exit 1
    fi

    APPNAME=
    WMNAME=
    if [ "$1" = "microsoft-edge" ];then
        APPNAME="microsoft-edge-stable"
        WMNAME="Microsoft​ Edge"
        WMNAME_FIX="Microsoft_Edge_Fix"
    elif [ "$1" = "alacritty" ];then
        APPNAME="alacritty"
        WMNAME="Alacritty"
        WMNAME_FIX="Alacritty_Fix"
    elif [ "$1" = "vscode" ];then
        APPNAME="code"
        WMNAME="Visual Studio Code"
        WMNAME_FIX="Visual_Studio_Code_Fix"
    elif [ "$1" = "dingtalk" ];then
        APPNAME="dingtalk-linux"
        WMNAME="DingTalk"
        WMNAME_FIX="DingTalk_Fix"
    elif [ "$1" = "st" ];then
        APPNAME="st"
        WMNAME="st"
        WMNAME_FIX="st_Fix"
    elif [ "$1" = "feishu" ];then
        APPNAME="feishu"
        WMNAME="Feishu"
        WMNAME_FIX="Feishu_Fix"
    fi

    alreadyOpenFix=$(wmctrl -l | grep "${WMNAME_FIX}" | grep -v grep)
    alreadyOpen=$(wmctrl -l | grep "${WMNAME}" | grep -v grep)

    # 优先显示Fix，若不存在则尝试显示一般，最后重新创建
    if [ -n "${alreadyOpenFix}" ];then
        wmctrl -a ${WMNAME_FIX}
    else
        if [ -n "${alreadyOpen}" ];then
            wmctrl -a ${WMNAME}
        else
            ${APPNAME} &
            sleep 3 # vscode打开需要比较长的时间
            declare -i cnt
            cnt=0
            while [ $cnt -lt 6 ]
            do
                echo while
                alreadyOpen=$(wmctrl -l | grep "${WMNAME}" | grep -v grep)
                if [ -n "${alreadyOpen}" ];then
                    wmctrl -r ${WMNAME} -T ${WMNAME_FIX}
                    echo ok
                    exit 0
                fi
                sleep 0.5
                cnt=$cnt+1
            done
        fi
    fi
}

appToggle $*
